
#include "BlockQueue.hpp"

void *create(void *args)
{
    // 拿到消费队列
    BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    while (true)
    {
        // 生产数据
        int tem = rand() % 17 + 19;
        bq->Push(tem);
        sleep(0.2);
    }

    return nullptr;
}

void *consume(void *args)
{
    // 拿到消费队列
    BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(args);
    while (true)
    {
        int get = 0;
        bq->Pop(&get);
        // cout<<"consumer get data : "<<get<<endl;
        sleep(0.15);
    }

    return nullptr;
}
void test1()
{
    srand((unsigned int)time(nullptr));
    BlockQueue<int> *Bq = new BlockQueue<int>(500);
    cout << "shop opened" << endl;

    // 生产和消费线程
    pthread_t creator1, consumer1;

    pthread_create(&consumer1, nullptr, consume, (void *)Bq);
    pthread_create(&creator1, nullptr, create, (void *)Bq);

    while (1)
    {
        cout << "nums left: " << Bq->GetSize() << endl;
        sleep(1);
    }
}
void test2()
{
    srand((unsigned int)time(nullptr));
    BlockQueue<int> *Bq = new BlockQueue<int>(500);
    cout << "shop opened" << endl;
    // 生产和消费线程
    pthread_t creator1, consumer1;
    pthread_t creator2, consumer2;
    pthread_t creator3, consumer3;
    pthread_t creator4, consumer4;
    pthread_t creator5, consumer5;
    pthread_t creator6, consumer6;

    pthread_create(&creator1, nullptr, create, (void *)Bq);
    pthread_create(&creator2, nullptr, create, (void *)Bq);
    pthread_create(&creator3, nullptr, create, (void *)Bq);
    pthread_create(&creator4, nullptr, create, (void *)Bq);
    pthread_create(&creator5, nullptr, create, (void *)Bq);
    pthread_create(&creator6, nullptr, create, (void *)Bq);

    pthread_create(&consumer1, nullptr, consume, (void *)Bq);
    pthread_create(&consumer2, nullptr, consume, (void *)Bq);
    pthread_create(&consumer3, nullptr, consume, (void *)Bq);
    pthread_create(&consumer4, nullptr, consume, (void *)Bq);
    pthread_create(&consumer5, nullptr, consume, (void *)Bq);
    pthread_create(&consumer6, nullptr, consume, (void *)Bq);
    while (1)
    {
        cout << "nums left: " << Bq->GetSize() << endl;
        sleep(1);
    }
}
int main()
{
    // 单生产单消费测试
    //test1();

    // 测试水平线的负反馈调节
    test2();

    return 0;
}
